<?php

namespace App\Http\Controllers\Api\V1\Frontend\Auth;

use Illuminate\Http\Request;
use App\Services\AuthService;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class IndexController extends Controller
{


    /**
     * 用户登陆
     * @param Request $request
     * @param AuthService $authService
     * @return mixed
     * @throws ValidationException
     */
    public function login(Request $request,AuthService $authService)
    {

        Validator::make($request->all(),[
            'username' => 'required|string',
            'password' => 'required|string'
        ])->validate();

        $data = $authService->login($request->only('username','password'));

        if ($data['code'] == 200){
            return $this->successful($data['data'],'登陆成功');
        }

        return $this->failed($data['message']);
    }
    /**
     * 用户登陆，只验证用户名
     * @param Request $request
     * @param AuthService $authService
     * @return mixed
     * @throws ValidationException
     */
    public function loginByUsername(Request $request,AuthService $authService)
    {
        Validator::make($request->all(),[
            'username' => 'required|string'
        ])->validate();

        $data = $authService->loginByUsername($request->only('username'));

        if ($data['code'] == 200){
            return $this->successful($data['data'],'登陆成功');
        }

        return $this->failed($data['message']);
    }

    /** 发送短信验证码
     * @param Request $request
     * @param AuthService $authService
     * @return mixed
     * @throws ValidationException
     */
    public function sendSMSVerifycode(Request $request,AuthService $authService){
        Validator::make($request->all(),[
            'username' => 'required|string'
        ],[
            'username.required' => '请选择先输入用户名'
        ])->validate();

        $data = $authService->sendSMSVerifycode($request->input('username'));

        if ($data['code'] == 200){
            return $this->successful($data['data'],'验证码发送成功');
        }

        return $this->failed($data['message']);
    }

    /**
     * 接口检测
     * @param Request $request
     * @param AuthService $authService
     * @return mixed
     */
    public function check(Request $request,AuthService $authService)
    {
        $data = $authService->check($request->header('authorization'));

        if ($data['code'] == 200){
            return $this->successful($data['data'],$data['message'],$data['status']);
        }

        return $this->failed($data['message']);
    }

    /**
     * 安全退出
     * @param AuthService $authService
     * @return mixed
     */
    public function logout(AuthService $authService)
    {
        $data = $authService->logout();

        if ($data['code'] == 200){
            return $this->successful($data['data'],'安全退出');
        }

        return $this->failed($data['message']);
    }
}
